package com.ysd.lis.service.lab.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.PubReport;
import com.ysd.lis.entity.ReportPreviewDto;
import com.ysd.lis.entity.SysParamSearchOutputDto;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.entity.bac.*;
import com.ysd.lis.entity.lab.LabMaininfo;
import com.ysd.lis.entity.lab.LabRptdetailBac;
import com.ysd.lis.entity.lab.LabRptdetailStaining;
import com.ysd.lis.entity.lab.LabRptmain;
import com.ysd.lis.mapper.bac.*;
import com.ysd.lis.mapper.lab.LabMaininfoMapper;
import com.ysd.lis.mapper.lab.LabRptdetailBacMapper;
import com.ysd.lis.mapper.lab.LabRptdetailStainingMapper;
import com.ysd.lis.mapper.lab.LabRptmainMapper;
import com.ysd.lis.mapper.pub.PubReportMapper;
import com.ysd.lis.request.BacGenerateReportRequestParam;
import com.ysd.lis.request.CommonPageDto;
import com.ysd.lis.request.SysParamFieldValueDto;
import com.ysd.lis.request.SysParamParam;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.SysParamValueService;
import com.ysd.lis.service.bac.BacDrugTestResultService;
import com.ysd.lis.service.bac.BacStainingResultService;
import com.ysd.lis.service.bac.BacTestResultService;
import com.ysd.lis.service.bac.BacWorkFlowService;
import com.ysd.lis.service.common.RedisSysParamHelper;
import com.ysd.lis.service.lab.*;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 检验报告记录 服务实现类
 * </p>
 *
 * @author Cfz
 * @since 2023-12-26
 */
@Service
public class LabRptmainServiceImpl extends ServiceImpl<LabRptmainMapper, LabRptmain> implements LabRptmainService {
    private static final Logger logger = LoggerFactory.getLogger(LabRptmainServiceImpl.class);
    @Autowired
    LabMaininfoMapper labMaininfoMapper;
    @Autowired
    LabMaininfoService labMaininfoService;

    @Autowired
    BacTestResultMapper bacTestResultMapper;
    @Autowired
    BacTestResultService bacTestResultService;

    @Autowired
    BacDrugTestResultMapper bacDrugTestResultMapper;
    @Autowired
    BacDrugTestResultService bacDrugTestResultService;

    @Autowired
    BacStainingResultMapper bacStainingResultMapper;
    @Autowired
    BacStainingResultService bacStainingResultService;

    @Autowired
    LabRptmainMapper labRptmainMapper;
    @Autowired
    LabRptmainService labRptmainService;

    @Autowired
    LabRptdetailBacMapper labRptdetailBacMapper;
    @Autowired
    LabRptdetailBacService labRptdetailBacService;

    @Autowired
    LabRptdetailStainingMapper labRptdetailStainingMapper;
    @Autowired
    LabRptdetailStainingService labRptdetailStainingService;

    @Autowired
    SysBasDictDetailService sysBasDictDetailService;

    @Autowired
    PubReportMapper pubReportMapper;
    @Autowired
    PubReportService pubReportService;
    @Autowired
    BacPublisSecReportMapper bacPublisSecReportMapper;
    @Autowired
    BacPublisFirstReportMapper bacPublisFirstReportMapper;
    @Autowired
    BacImageResultMapper bacImageResultMapper;
    @Autowired
    RedisSysParamHelper redisSysParamHelper;
    @Autowired
    BacWorkFlowService bacWorkFlowService;
    @Autowired
    SysParamValueService sysParamValueService;

    @Override
    public Result BacGenerateReport(BacGenerateReportRequestParam input) throws JsonProcessingException {
        List<ReportPreviewDto> resList = new ArrayList<>();
        LambdaQueryWrapper<LabMaininfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabMaininfo::getDelFlag, 0);
        queryWrapper.eq(LabMaininfo::getSampleNo, input.getSampleNo());
        Timestamp timestamp = new Timestamp(input.getSampleda().getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(timestamp);
        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
        queryWrapper.ge(LabMaininfo::getSampleda, startTime);
        queryWrapper.le(LabMaininfo::getSampleda, endTime);
        queryWrapper.eq(LabMaininfo::getRptGroup, input.getRptGroup());
        LabMaininfo labMaininfo = labMaininfoMapper.selectOne(queryWrapper);

        if (BeanUtil.isEmpty(labMaininfo)) {
            return Result.fail("查无检验记录");
        }

        /*是否审核，如果已审核，取最终报告,不再生成*/
        if (ToolsUtils.isNotEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().compareTo(new BigDecimal(2)) >= 0) {
            MPJLambdaWrapper<LabRptmain> queryWrapperSerach = new MPJLambdaWrapper<>();
            queryWrapperSerach.selectAll(LabRptmain.class);
            queryWrapperSerach.selectAs("pubrpt", PubReport::getName, LabRptmain::getTemplateName);
            queryWrapperSerach.eq(LabRptmain::getDelFlag, 0);
            queryWrapperSerach.eq(LabRptmain::getIsFinalReport, 1);
            queryWrapperSerach.eq(LabRptmain::getRptGroup, labMaininfo.getRptGroup()).eq(LabRptmain::getSampleda, labMaininfo.getSampleda()).eq(LabRptmain::getSampleNo, labMaininfo.getSampleNo());
            queryWrapperSerach.leftJoin(PubReport.class, "pubrpt", p -> p.eq(PubReport::getId, LabRptmain::getRptTemplateCode).isNotNull(PubReport::getCode));
            List<LabRptmain> labRptmainList = labRptmainMapper.selectList(queryWrapperSerach);

            if (CollectionUtils.isNotEmpty(labRptmainList)) {
                int i = 0;
                for (LabRptmain m : labRptmainList) {
                    ReportPreviewDto _m = new ReportPreviewDto();
                    _m.setId(m.getId());
                    _m.setReportId(m.getRptTemplateCode());
                    _m.setIsChecked(i == 0);
                    _m.setReportTemplateName(m.getTemplateName());
                    resList.add(_m);
                    i++;
                }
                return Result.succ(1, "生成成功", resList);
            }
        }

        /*清空已存在的数据*/
        deleteExistRptRecords(input.getRptGroup(), input.getSampleda(), input.getSampleNo());

        /*查询出细菌鉴定结果*/
        BacTestResult bacTestResult = new BacTestResult();
        bacTestResult.setRptGroup(input.getRptGroup());
        bacTestResult.setSampleda(input.getSampleda());
        bacTestResult.setSampleNo(input.getSampleNo());
        List<BacTestResult> BacTestResultList = bacTestResultService.findBacTestResultArray(bacTestResult);


        //不允许用ID产生的后果,无法用in
        List<BacDrugTestResult> BacDrugTestResultList = new ArrayList<>();
        if (!BacTestResultList.isEmpty()) {
            BacTestResultList.forEach(a -> {
                MPJLambdaWrapper<BacDrugTestResult> bacDrugTestResultQueryWrapper = new MPJLambdaWrapper<>();
                bacDrugTestResultQueryWrapper.eq(BacDrugTestResult::getDelFlag, 0);
                bacDrugTestResultQueryWrapper.eq(BacDrugTestResult::getIsolateNum, a.getIsolateNum());
                bacDrugTestResultQueryWrapper.eq(BacDrugTestResult::getSampleda, a.getSampleda());
                bacDrugTestResultQueryWrapper.eq(BacDrugTestResult::getSampleNo, a.getSampleNo());
                bacDrugTestResultQueryWrapper.eq(BacDrugTestResult::getRptGroup, a.getRptGroup());
                bacDrugTestResultQueryWrapper.eq(BacDrugTestResult::getTestFlowNo, a.getTestFlowNo());
                bacDrugTestResultQueryWrapper.eq(BacDrugTestResult::getTestNodeNo, a.getTestNodeNo());
                BacDrugTestResultList.addAll(bacDrugTestResultMapper.selectList(bacDrugTestResultQueryWrapper));
            });
        }
        /*查询出药敏结果*/

        /*查询出染色结果*/
        BacStainingResult bacStainingResult = new BacStainingResult();
        bacStainingResult.setRptGroup(input.getRptGroup());
        bacStainingResult.setSampleda(input.getSampleda());
        bacStainingResult.setSampleNo(input.getSampleNo());

        List<BacStainingResult> BacStainingResultList = bacStainingResultService.findBacStainingResultArray(bacStainingResult);

        //优先处理鉴定药敏结果，每个药敏一个报告记录

        List<LabRptmain> rptMainList = new ArrayList<>();/*报告记录*/
        List<LabRptdetailBac> rptDetailBacList = new ArrayList<>();/*报告记录明细 细菌鉴定结果*/
        List<LabRptdetailStaining> rptDetailStainingList = new ArrayList<>();/*报告记录明细 染色结果*/

        SysUser sysUser = RedisUserManager.getUser();

        SysParamParam sysp1 = new SysParamParam();
        sysp1.setParamCode("xtxxcs");
        sysp1.setField("wswwymjgsfywjgmb");
        List<SysParamFieldValueDto> r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
        Boolean isWswwymjgsfywjgmb = false;
        if (!r1.isEmpty()) {
            if (r1.get(0).getValue().equals("1")) {
                isWswwymjgsfywjgmb=true;
            }
        }
        //004   药敏报告  008细菌阳性无药敏结果 (有药敏结果用004,没有用008)
        String reportCode="";
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(BacDrugTestResultList)&& isWswwymjgsfywjgmb){
            reportCode="008";
        }else {
            reportCode="004";
        }
        PubReport ympReport = pubReportService.getPubReportByDictDetailVaule(reportCode);

        /*报告单元系统选项，微生物药敏报告是否拆分报告*/
        /*报告单元系统选项，微生物药敏报告是否拆分报告 wswymbgsfhbbg*/
        String wswymbgsfhbbg = "";
        try {
            SysParamSearchOutputDto paramResult = redisSysParamHelper.getValueByBGDYXTXXCSParam(ympReport.getOrgId(), "wswymbgsfhbbg", input.getRptGroup(), null);
            wswymbgsfhbbg = paramResult.getValueStr();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (ToolsUtils.isNotEmpty(BacTestResultList)) {
            //
            if (ToolsUtils.isNotEmpty(wswymbgsfhbbg) && "1".equals(wswymbgsfhbbg)) {
                for (BacTestResult m : BacTestResultList) {
                    if (ToolsUtils.isNotEmpty(m.getGermNo())) {
                        /*主表记录*/
                        // 获取UUID的前19位作为ASSIGN_ID
                        String assignId = IdUtil.getSnowflake().nextId() + "";
                        LabRptmain _m = new LabRptmain();
                        if (StringUtils.isNotBlank(sysUser.getOrgId())) {
                            _m.setOrgId(sysUser.getOrgId());
                        }
                        _m.setMainInfoId(m.getId());
                        _m.setIsFinalReport(input.getIsFinalRpt());
                        _m.setRptGroup(input.getRptGroup());
                        _m.setSampleda(input.getSampleda());
                        _m.setSampleNo(input.getSampleNo());
                        _m.setPublishDoctor(sysUser.getUsername());
                        _m.setPublishDoctorNa(sysUser.getRealname());
                        _m.setRptGroup(labMaininfo.getRptGroup());
                        _m.setSampleda(labMaininfo.getSampleda());
                        _m.setSampleNo(labMaininfo.getSampleNo());
                        _m.setId(assignId);
                        _m.setRptCode(assignId);
                        _m.setTemplateName(ToolsUtils.isNotEmpty(ympReport) && ToolsUtils.isNotEmpty(ympReport.getName()) ? ympReport.getName() : "细菌药敏报告.rdlx");
                        _m.setRptTemplateCode(ToolsUtils.isNotEmpty(ympReport) && ToolsUtils.isNotEmpty(ympReport.getId()) ? ympReport.getId() : "1772906159338954753");

                        _m.setPageUnit("A5");
                        rptMainList.add(_m);

                        /*细菌鉴定结果明细*/
                        LabRptdetailBac _mdb = new LabRptdetailBac();
                        if (StringUtils.isNotBlank(sysUser.getOrgId())) {
                            _mdb.setOrgId(sysUser.getOrgId());
                        }
                        _mdb.setBacTestResultId(m.getId());
                        _mdb.setRptMainCode(_m.getRptCode());
                        rptDetailBacList.add(_mdb);

                        /*染色结果明细*/
                        List<BacStainingResult> BacStainingResultArr = BacStainingResultList.stream().filter(p -> StringUtils.isBlank(p.getIsolateNum()) || p.getIsolateNum().equals(m.getIsolateNum())).collect(Collectors.toList());

                        if (!BacStainingResultArr.isEmpty()) {
                            for (BacStainingResult _op : BacStainingResultArr) {
                                LabRptdetailStaining _mds = new LabRptdetailStaining();
                                _mds.setRptMainCode(_m.getRptCode());
                                _mds.setBacStainingResultId(_op.getId());
                                rptDetailStainingList.add(_mds);
                            }
                        }
                    }
                }
            } else {
                List<BacTestResult> ymresultList1 = BacTestResultList.stream().filter(p -> ToolsUtils.isNotEmpty(p.getGermNo())).collect(Collectors.toList());
                BacTestResult m = ToolsUtils.isEmpty(ymresultList1) ? null : ymresultList1.get(0);
                if (Objects.nonNull(m)&&ToolsUtils.isNotEmpty(m.getGermNo())) {
                    /*主表记录*/
                    // 获取UUID的前19位作为ASSIGN_ID
                    String assignId = IdUtil.getSnowflake().nextId() + "";
                    LabRptmain _m = new LabRptmain();
                    if (StringUtils.isNotBlank(sysUser.getOrgId())) {
                        _m.setOrgId(sysUser.getOrgId());
                    }
                    _m.setMainInfoId(m.getId());
                    _m.setIsFinalReport(input.getIsFinalRpt());
                    _m.setRptGroup(input.getRptGroup());
                    _m.setSampleda(input.getSampleda());
                    _m.setSampleNo(input.getSampleNo());
                    _m.setPublishDoctor(sysUser.getUsername());
                    _m.setPublishDoctorNa(sysUser.getRealname());
                    _m.setRptGroup(labMaininfo.getRptGroup());
                    _m.setSampleda(labMaininfo.getSampleda());
                    _m.setSampleNo(labMaininfo.getSampleNo());
                    _m.setId(assignId);
                    _m.setRptCode(assignId);
                    _m.setTemplateName(ToolsUtils.isNotEmpty(ympReport) && ToolsUtils.isNotEmpty(ympReport.getName()) ? ympReport.getName() : "细菌药敏报告.rdlx");
                    _m.setRptTemplateCode(ToolsUtils.isNotEmpty(ympReport) && ToolsUtils.isNotEmpty(ympReport.getId()) ? ympReport.getId() : "1772906159338954753");

                    _m.setPageUnit("A5");
                    rptMainList.add(_m);

                    /*细菌鉴定结果明细*/
                    LabRptdetailBac _mdb = new LabRptdetailBac();
                    if (StringUtils.isNotBlank(sysUser.getOrgId())) {
                        _mdb.setOrgId(sysUser.getOrgId());
                    }
                    _mdb.setBacTestResultId(m.getId());
                    _mdb.setRptMainCode(_m.getRptCode());
                    rptDetailBacList.add(_mdb);

                    /*染色结果明细*/
                    List<BacStainingResult> BacStainingResultArr = BacStainingResultList.stream().filter(p -> StringUtils.isBlank(p.getIsolateNum()) || p.getIsolateNum().equals(m.getIsolateNum())).collect(Collectors.toList());

                    if (!BacStainingResultArr.isEmpty()) {
                        for (BacStainingResult _op : BacStainingResultArr) {
                            LabRptdetailStaining _mds = new LabRptdetailStaining();
                            _mds.setRptMainCode(_m.getRptCode());
                            _mds.setBacStainingResultId(_op.getId());
                            rptDetailStainingList.add(_mds);
                        }
                    }
                }
            }
        }


        //处理非药敏鉴定结果及涂片结果，所有共用一个报表记录
        //List<String> resArr1 = rptDetailBacList.stream().map(LabRptdetailBac::getBacTestResultId).collect(Collectors.toList());
        //List<String> resArr2 = rptDetailStainingList.stream().map(LabRptdetailStaining::getBacStainingResultId).collect(Collectors.toList());
        //List<BacTestResult> arr1 = resArr1.isEmpty() ? new ArrayList<>() : BacTestResultList.stream().filter(p -> !resArr1.contains(p.getId())).collect(Collectors.toList());
        //List<BacStainingResult> arr2 = resArr2.isEmpty() ? new ArrayList<>() : BacStainingResultList.stream().filter(p -> !resArr2.contains(p.getId())).collect(Collectors.toList());

        /*获取采用哪个阴性报告*/
        PubReport yxpReport = pubReportService.getPubReportByDictDetailVaule("003");
        /*阴性结果报告*/
        for (BacTestResult m : BacTestResultList) {
            if (ToolsUtils.isNotEmpty(m.getGermNo())) {
                continue;
            }
            String assignId = IdUtil.getSnowflake().nextId() + "";
            LabRptmain _m = new LabRptmain();
            if (StringUtils.isNotBlank(sysUser.getOrgId())) {
                _m.setOrgId(sysUser.getOrgId());
            }
            _m.setMainInfoId(m.getId());
            _m.setIsFinalReport(input.getIsFinalRpt());
            _m.setSampleNo(input.getSampleNo());
            _m.setSampleda(input.getSampleda());
            _m.setRptGroup(input.getRptGroup());

            _m.setPublishDoctor(sysUser.getUsername());
            _m.setPublishDoctorNa(sysUser.getRealname());
            _m.setRptGroup(labMaininfo.getRptGroup());
            _m.setSampleda(labMaininfo.getSampleda());
            _m.setSampleNo(labMaininfo.getSampleNo());
            _m.setId(assignId);
            _m.setRptCode(assignId);
            _m.setTemplateName(ToolsUtils.isNotEmpty(yxpReport) && ToolsUtils.isNotEmpty(yxpReport.getName()) ? yxpReport.getName() : "细菌阴性报告.rdlx");
            _m.setRptTemplateCode(ToolsUtils.isNotEmpty(yxpReport) && ToolsUtils.isNotEmpty(yxpReport.getId()) ? yxpReport.getId() : "1772906224224837633");
            _m.setPageUnit("A5");
            rptMainList.add(_m);
        }
        /*if (arr1.size() > 0 || arr2.size() > 0) {
            String assignId = IdUtil.getSnowflake().nextId() + "";
            LabRptmain _m = new LabRptmain();
            if (StringUtils.isNotBlank(sysUser.getOrgId())) {
                _m.setOrgId(sysUser.getOrgId());
            }
            _m.setIsFinalReport(input.getIsFinalRpt());
            _m.setSampleNo(input.getSampleNo());
            _m.setSampleda(input.getSampleda());
            _m.setRptGroup(input.getRptGroup());

            _m.setPublishDoctor(sysUser.getUsername());
            _m.setPublishDoctorNa(sysUser.getRealname());
            _m.setRptGroup(labMaininfo.getRptGroup());
            _m.setSampleda(labMaininfo.getSampleda());
            _m.setSampleNo(labMaininfo.getSampleNo());
            _m.setId(assignId);
            _m.setRptCode(assignId);
            _m.setTemplateName(ToolsUtils.isNotEmpty(yxpReport) && ToolsUtils.isNotEmpty(yxpReport.getName()) ? yxpReport.getName() : "细菌阴性报告.rdlx");
            _m.setRptTemplateCode(ToolsUtils.isNotEmpty(yxpReport) && ToolsUtils.isNotEmpty(yxpReport.getId()) ? yxpReport.getId() : "1772906224224837633");
            _m.setPageUnit("A5");
            rptMainList.add(_m);
            //鉴定结果
            for (BacTestResult m : arr1) {
                LabRptdetailBac _mdb = new LabRptdetailBac();
                if (StringUtils.isNotBlank(sysUser.getOrgId())) {
                    _mdb.setOrgId(sysUser.getOrgId());
                }
                _mdb.setBacTestResultId(m.getId());
                _mdb.setRptMainCode(_m.getRptCode());
                rptDetailBacList.add(_mdb);
            }

            //染色结果
            for (BacStainingResult m : arr2) {
                LabRptdetailStaining _mds = new LabRptdetailStaining();
                _mds.setRptMainCode(_m.getRptCode());
                _mds.setBacStainingResultId(m.getId());
                rptDetailStainingList.add(_mds);
            }
        }*/

        if (rptMainList.size() <= 0) {
            return Result.fail("没有要生成的报告");
        }

        boolean i1 = this.saveBatch(rptMainList);
        if (i1 && rptDetailBacList.size() > 0) {
            labRptdetailBacService.saveBatch(rptDetailBacList);
        }

        if (i1 && rptDetailStainingList.size() > 0) {
            labRptdetailStainingService.saveBatch(rptDetailStainingList);
        }


        int i = 0;
        for (LabRptmain m : rptMainList) {
            ReportPreviewDto _m = new ReportPreviewDto();
            _m.setId(m.getId());
            _m.setReportId(m.getRptTemplateCode());
            _m.setIsChecked(i == 0);
            _m.setReportTemplateName(m.getTemplateName());
            resList.add(_m);
            i++;
        }
        return Result.succ(1, "生成成功", resList);
    }

    @Override
    public Result BacGenerateFirstReport(BacGenerateReportRequestParam input) {
        CommonPageDto pageParam = new CommonPageDto();
        pageParam.setCode("YWBD");
        Result dictResult = sysBasDictDetailService.findDictDetailList(pageParam);
        if (ToolsUtils.isEmpty(dictResult)) {
            return Result.fail("未找到相关字典数据");
        }
        List<Map<String, Object>> data = (List<Map<String, Object>>) dictResult.getData();

        List<Map<String, Object>> filteredList = data.stream().filter(map -> "1745380128773828610".equals(map.get("moduleId")) && "001".equals(map.get("pointsCode"))).collect(Collectors.toList());
        if (ToolsUtils.isEmpty(filteredList)) {
            return Result.fail("未找到相关字典数据");
        }

        String pointId = filteredList.get(0).get("commonId").toString();

        /*计算使用的模板Id,模板名称*/
        LambdaQueryWrapper<PubReport> pubRptQuery = new LambdaQueryWrapper();
        pubRptQuery.eq(PubReport::getDelFlag, 0);
        pubRptQuery.eq(PubReport::getPointsId, pointId);
        pubRptQuery.eq(PubReport::getIsUse, 1);
        List<PubReport> pubReportList = pubReportMapper.selectList(pubRptQuery);
        if (ToolsUtils.isEmpty(pubReportList)) {
            return Result.fail("未找到相关模板数据");
        }
        PubReport pubReport = pubReportList.get(0);

        /*查询初级报告发布*/
        LambdaQueryWrapper<BacPublisFirstReport> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        Timestamp timestamp = new Timestamp(input.getSampleda().getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(timestamp);
        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
        lambdaQueryWrapper.ge(BacPublisFirstReport::getSampleda, startTime);
        lambdaQueryWrapper.le(BacPublisFirstReport::getSampleda, endTime);
        lambdaQueryWrapper.eq(BacPublisFirstReport::getRptGroup, input.getRptGroup());
        lambdaQueryWrapper.eq(BacPublisFirstReport::getSampleNo, input.getSampleNo());
        lambdaQueryWrapper.eq(BacPublisFirstReport::getTestFlowNo, input.getTestFlowNo());
        lambdaQueryWrapper.eq(BacPublisFirstReport::getTestNodeNo, input.getTestNodeNo());
        lambdaQueryWrapper.and(p -> p.ne(BacPublisFirstReport::getIsCancel, 1).or().isNull(BacPublisFirstReport::getIsCancel));
        //lambdaQueryWrapper.eq(BacPublisSecReport::getStrainNo,input.getStrainNo());
        List<BacPublisFirstReport> bacPublisSecReports = bacPublisFirstReportMapper.selectList(lambdaQueryWrapper);

        SysUser sysUser = RedisUserManager.getUser();
        List<LabRptmain> rptMainList = new ArrayList<>();
        List<LabRptmain> rptMainListNoSave = new ArrayList<>();

        List<ReportPreviewDto> resList = new ArrayList<>();
        if (ToolsUtils.isNotEmpty(bacPublisSecReports)) {
            String idsStr = bacPublisSecReports.stream().map(BacPublisFirstReport::getId).collect(Collectors.joining(","));
            ReportPreviewDto _m = new ReportPreviewDto();
            _m.setId(idsStr);
            _m.setReportId(pubReport.getId());
            _m.setIsChecked(true);
            _m.setReportTemplateName(pubReport.getName());
            resList.add(_m);

            String assignId = IdUtil.getSnowflake().nextId() + "";
            LabRptmain _mm = new LabRptmain();
            if (StringUtils.isNotBlank(sysUser.getOrgId())) {
                _mm.setOrgId(sysUser.getOrgId());
            }
            _mm.setIsFinalReport(1);
            _mm.setSampleNo(input.getSampleNo());
            _mm.setSampleda(input.getSampleda());
            _mm.setRptGroup(input.getRptGroup());
            _mm.setPublishDoctor(sysUser.getUsername());
            _mm.setPublishDoctorNa(sysUser.getRealname());
            _mm.setRptGroup(input.getRptGroup());
            _mm.setSampleda(input.getSampleda());
            _mm.setSampleNo(input.getSampleNo());
            _mm.setId(assignId);
            _mm.setRptCode(pubReport.getCode());
            _mm.setTemplateName(ToolsUtils.isNotEmpty(pubReport) && ToolsUtils.isNotEmpty(pubReport.getName()) ? pubReport.getName() : "细菌初级报告报告.rdlx");
            _mm.setRptTemplateCode(ToolsUtils.isNotEmpty(pubReport) && ToolsUtils.isNotEmpty(pubReport.getId()) ? pubReport.getId() : "");
            _mm.setPageUnit("A5");
            _mm.setIsFirstRpt(true);
            _mm.setFirstRptId(idsStr);
            rptMainListNoSave.add(_mm);
        }

        /*阴性报告*/
        PubReport yxpReport = pubReportService.getPubReportByDictDetailVaule("003");
        /*查询出细菌鉴定结果*/
        BacTestResult bacTestResult = new BacTestResult();
        bacTestResult.setRptGroup(input.getRptGroup());
        bacTestResult.setSampleda(input.getSampleda());
        bacTestResult.setSampleNo(input.getSampleNo());
        List<BacTestResult> BacTestResultList = bacTestResultService.findBacTestResultArray(bacTestResult);
        //List<BacTestResult> BacTestResultListYX = new ArrayList<>();//BacTestResultList.stream().filter(p->p.)
        /*找出阴性报告*/
        /*for (BacTestResult m : BacTestResultList) {
            if (ToolsUtils.isEmpty(m.getGermNo())) {
                BacTestResultListYX.add(m);
            }
        }*/


        /*阴性结果报告*/
        for (BacTestResult m : BacTestResultList) {
            if (ToolsUtils.isNotEmpty(m.getGermNo())) {
                continue;
            }
            if (ToolsUtils.isEmpty(m.getCulMediumNo())) {
                continue;
            }
            if (CollectionUtils.isNotEmpty(input.getCulMediumNos()) && !input.getCulMediumNos().contains(m.getCulMediumNo())) {
                continue;
            }
            String assignId = IdUtil.getSnowflake().nextId() + "";
            LabRptmain _m = new LabRptmain();
            if (StringUtils.isNotBlank(sysUser.getOrgId())) {
                _m.setOrgId(sysUser.getOrgId());
            }
            _m.setIsFinalReport(1);
            _m.setSampleNo(input.getSampleNo());
            _m.setSampleda(input.getSampleda());
            _m.setRptGroup(input.getRptGroup());

            _m.setPublishDoctor(sysUser.getUsername());
            _m.setPublishDoctorNa(sysUser.getRealname());
            _m.setRptGroup(input.getRptGroup());
            _m.setSampleda(input.getSampleda());
            _m.setSampleNo(input.getSampleNo());
            _m.setId(assignId);
            _m.setRptCode(yxpReport.getCode());
            _m.setTemplateName(ToolsUtils.isNotEmpty(yxpReport) && ToolsUtils.isNotEmpty(yxpReport.getName()) ? yxpReport.getName() : "细菌阴性报告.rdlx");
            _m.setRptTemplateCode(ToolsUtils.isNotEmpty(yxpReport) && ToolsUtils.isNotEmpty(yxpReport.getId()) ? yxpReport.getId() : "1772906224224837633");
            _m.setPageUnit("A5");
            rptMainList.add(_m);
        }

        if (rptMainList.size() <= 0 && rptMainListNoSave.size() <= 0) {
            return Result.fail("没有要生成的报告");
        }

        boolean i1 = this.saveBatch(rptMainList);
        rptMainList.addAll(rptMainListNoSave);
        List<ReportPreviewDto> resCollection = new ArrayList<>();
        int i = 0;
        for (LabRptmain m : rptMainList) {
            ReportPreviewDto _m = new ReportPreviewDto();
            _m.setId(m.getId());
            if (ToolsUtils.isNotEmpty(m.getIsFirstRpt()) && m.getIsFirstRpt()) {
                _m.setId(m.getFirstRptId());
            }
            _m.setReportId(m.getRptTemplateCode());
            _m.setIsChecked(i == 0);
            _m.setReportTemplateName(m.getTemplateName());
            resCollection.add(_m);
            i++;
        }
        return CollectionUtils.isNotEmpty(resCollection) ? Result.succ(1, "成功", resCollection) : Result.fail("没有要生成的报告");
    }

    @Override
    public Result BacGenerateSecondReport(BacGenerateReportRequestParam input) {
        CommonPageDto pageParam = new CommonPageDto();
        pageParam.setCode("YWBD");
        Result dictResult = sysBasDictDetailService.findDictDetailList(pageParam);
        if (ToolsUtils.isEmpty(dictResult)) {
            return Result.fail("未找到相关字典数据");
        }
        List<Map<String, Object>> data = (List<Map<String, Object>>) dictResult.getData();

        List<Map<String, Object>> filteredList = data.stream().filter(map -> "1745380128773828610".equals(map.get("moduleId")) && "002".equals(map.get("pointsCode"))).collect(Collectors.toList());
        if (ToolsUtils.isEmpty(filteredList)) {
            return Result.fail("未找到相关字典数据");
        }

        String pointId = filteredList.get(0).get("commonId").toString();

        /*查询是否有图片*/
        LambdaQueryWrapper<BacImageResult> bacImageResultQuery = new LambdaQueryWrapper<>();
        bacImageResultQuery.eq(BacImageResult::getDelFlag, 0);
        bacImageResultQuery.eq(BacImageResult::getSampleNo, input.getSampleNo());
        bacImageResultQuery.eq(BacImageResult::getIsSelected, 1);
        bacImageResultQuery.in(BacImageResult::getRptGroup, input.getRptGroup());
        bacImageResultQuery.in(BacImageResult::getSampleda, input.getSampleda());
        bacImageResultQuery.in(BacImageResult::getTestFlowNo, input.getTestFlowNo());
        bacImageResultQuery.in(BacImageResult::getTestNodeNo, input.getTestNodeNo());
        //增加菌株匹配选择，若菌株号存在，则匹配
        bacImageResultQuery.in(ToolsUtils.isNotEmpty(input.getStrainNo()), BacImageResult::getIsolateNum, input.getStrainNo());
        int imgCount = bacImageResultMapper.selectCount(bacImageResultQuery);
        /*计算使用的模板Id,模板名称*/
        LambdaQueryWrapper<PubReport> pubRptQuery = new LambdaQueryWrapper();
        pubRptQuery.eq(PubReport::getDelFlag, 0);
        pubRptQuery.eq(PubReport::getPointsId, pointId);
        if (imgCount > 0) {
            pubRptQuery.eq(PubReport::getIncludeImages, 1);
        }
        pubRptQuery.eq(PubReport::getIsUse, 1);

        List<PubReport> pubReportList = pubReportMapper.selectList(pubRptQuery);
        if (ToolsUtils.isEmpty(pubReportList)) {
            return Result.fail("未找到相关模板数据");
        }
        PubReport pubReport = pubReportList.get(0);

        /*查询二级报告发布*/
        LambdaQueryWrapper<BacPublisSecReport> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        Timestamp timestamp = new Timestamp(input.getSampleda().getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(timestamp);
        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
        lambdaQueryWrapper.ge(BacPublisSecReport::getSampleda, startTime);
        lambdaQueryWrapper.le(BacPublisSecReport::getSampleda, endTime);
        lambdaQueryWrapper.eq(BacPublisSecReport::getRptGroup, input.getRptGroup());
        lambdaQueryWrapper.eq(BacPublisSecReport::getSampleNo, input.getSampleNo());
        lambdaQueryWrapper.eq(BacPublisSecReport::getTestFlowNo, input.getTestFlowNo());
        lambdaQueryWrapper.eq(BacPublisSecReport::getTestNodeNo, input.getTestNodeNo());
        lambdaQueryWrapper.and(p -> p.ne(BacPublisSecReport::getIsCancel, 1).or().isNull(BacPublisSecReport::getIsCancel));
        List<BacPublisSecReport> bacPublisSecReports = bacPublisSecReportMapper.selectList(lambdaQueryWrapper);

        List<ReportPreviewDto> resList = new ArrayList<>();
        if (ToolsUtils.isNotEmpty(bacPublisSecReports)) {
            String idsStr = bacPublisSecReports.stream().map(BacPublisSecReport::getId).collect(Collectors.joining(","));
            ReportPreviewDto _m = new ReportPreviewDto();
            _m.setId(idsStr);
            _m.setReportId(pubReport.getId());
            _m.setIsChecked(true);
            _m.setReportTemplateName(pubReport.getName());
            resList.add(_m);
        }

        return ToolsUtils.isNotEmpty(bacPublisSecReports) ? Result.succ(1, "成功", resList) : Result.fail("未发布二级报告");
    }

    /*自动生成报告*/
    @Override
    public Result GenerateRptmainAutoAsync() {
//        MPJLambdaWrapper<LabRptmain> qRptmainWrapper = new MPJLambdaWrapper<>();
//        String[] columns = {"MAIN_INFO_ID"};
//        qRptmainWrapper.select(columns);
//        qRptmainWrapper.eq(LabRptmain::getDelFlag, 0);
//        qRptmainWrapper.eq(LabRptmain::getIsFinalReport, 1);
//        List<LabRptmain> labRptmainList = labRptmainMapper.selectList(qRptmainWrapper);
//        List<String> mainIds = labRptmainList.stream().map(LabRptmain::getMainInfoId).collect(Collectors.toList());

        int total = 0;
        //按照月表来跑
        DateTime startTime = DateUtil.parse("2016-12", "yyyy-MM");
        DateTime endTime = DateUtil.parse("2022-09", "yyyy-MM");
        for (int j = 1; DateUtil.compare(startTime, endTime) < 0; j++) {
            startTime = DateUtil.offsetMonth(startTime, 1);
            Date endTime2 = DateUtil.offsetMonth(startTime, 1);
            MPJLambdaWrapper<LabMaininfo> queryWrapper = new MPJLambdaWrapper<>();
            queryWrapper.selectAll(LabMaininfo.class);
            queryWrapper.selectAs("chker", SysUser::getRealname, LabMaininfo::getChkDoctorNa);
            queryWrapper.leftJoin(SysUser.class, "chker", p -> p.eq(SysUser::getUsername, LabMaininfo::getChkDoctor).eq(SysUser::getDelFlag, 0));
            queryWrapper.eq(LabMaininfo::getIsChk, new BigDecimal(2));
            queryWrapper.eq(LabMaininfo::getDelFlag, 0);
            queryWrapper.eq(LabRptmain::getDelFlag, 0);
            //queryWrapper.notIn(!labRptmainList.isEmpty(), LabMaininfo::getId, mainIds);
            StringBuffer existssql = new StringBuffer("select 1 from LAB_RPTMAIN t2 where DEL_FLAG=0 and IS_FINAL_REPORT=1 and t.ID=t2.MAIN_INFO_ID");
            queryWrapper.notExists(existssql.toString());
            queryWrapper.between(LabMaininfo::getSampleda, startTime, endTime2);
            List<LabMaininfo> list = labMaininfoMapper.selectList(queryWrapper);
            int i = 0;
            for (LabMaininfo m : list) {
                try {
                    labMaininfoService.previewRpt(m, 2);
                    System.out.println(startTime + "→→→→→→→→→→→→→→→→→→→第" + (i + 1) + "/" + list.size() + "条已处理");
                    total++;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                i++;
            }
        }
        return Result.succ(1, "本次生成:" + total + "条数据", null);
    }


    /*lis接口回调自动生成报告*/
    @Override
    public void LisGenerateRptmainAutoAsync(LabMaininfo m) {
        try {
            labMaininfoService.previewRpt(m, 2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*更换报告单重新生成报告-原有报告单删除*/
    @Override
    public Result ReGenerateRptmain() {
        /*查询出已删除的报告单模板*/
        MPJLambdaWrapper<PubReport> pubReportWrapper = new MPJLambdaWrapper<>();
        pubReportWrapper.eq(PubReport::getDelFlag, 1);
        List<PubReport> pubReports = pubReportMapper.selectList(pubReportWrapper);
        List<String> delReports = pubReports.stream().map(PubReport::getId).collect(Collectors.toList());

        MPJLambdaWrapper<LabRptmain> qRptmainWrapper = new MPJLambdaWrapper<>();
        String[] columns = {"MAIN_INFO_ID"};
        qRptmainWrapper.select(columns);
        qRptmainWrapper.eq(LabRptmain::getDelFlag, 0);
        qRptmainWrapper.eq(LabRptmain::getIsFinalReport, 1);
        qRptmainWrapper.in(LabRptmain::getRptTemplateCode, delReports);
        List<LabRptmain> labRptmainList = labRptmainMapper.selectList(qRptmainWrapper);
        List<String> mainIds = labRptmainList.stream().map(LabRptmain::getMainInfoId).collect(Collectors.toList());

        /*查询出相关的 上机记录*/
        MPJLambdaWrapper<LabMaininfo> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.eq(LabMaininfo::getDelFlag, 0);
        queryWrapper.eq(LabMaininfo::getIsChk, new BigDecimal(2));
        queryWrapper.in(LabMaininfo::getId, mainIds);
        List<LabMaininfo> list = labMaininfoMapper.selectList(queryWrapper);
        List<String> succList = new ArrayList<>();
        List<String> errorList = new ArrayList<>();
        int i = 1;
        for (LabMaininfo m : list) {
            try {
                labMaininfoService.previewRpt(m, 2);
                succList.add(i + "成功：" + m.getRptGroup() + "," + m.getSampleNo() + "," + m.getSampleda());
            } catch (Exception e) {
                errorList.add("失败：" + m.getRptGroup() + "," + m.getSampleNo() + "," + m.getSampleda());
                e.printStackTrace();
            }
            i++;
        }
        succList.addAll(errorList);
        return Result.succ(1, "成功", succList);
    }

    /*微生物重打标签*/
    @Override
    public Result RePrintLabel(String sltWorkFlowNo) {
        if (StringUtils.isNotBlank(sltWorkFlowNo)) {
            BacWorkFlow oneByNo = bacWorkFlowService.findOneByNo(sltWorkFlowNo);
            if (Objects.nonNull(oneByNo) && StringUtils.isNotBlank(oneByNo.getReportTemplateId())) {
                PubReport report = pubReportService.getById(oneByNo.getReportTemplateId());
                ReportPreviewDto _m = new ReportPreviewDto();
                _m.setId(null);
                _m.setReportId(report.getId());
                _m.setIsChecked(false);
                _m.setReportTemplateName(report.getName());
                return Result.succ(1, "成功", _m);
            }
        }
        PubReport labelPubReport = pubReportService.getPubReportByDictDetailVaule("005");
        ReportPreviewDto _m = new ReportPreviewDto();
        _m.setId(null);
        _m.setReportId(ToolsUtils.isNotEmpty(labelPubReport) ? labelPubReport.getId() : null);
        _m.setIsChecked(false);
        _m.setReportTemplateName(ToolsUtils.isNotEmpty(labelPubReport) ? labelPubReport.getName() : null);
        return Result.succ(1, "成功", _m);
    }


    private void deleteExistRptRecords(String rptGroup, Timestamp sampleda, String sampleNo) {
        /*查询报告主表*/
        LambdaQueryWrapper<LabRptmain> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabRptmain::getDelFlag, 0);
//        queryWrapper.eq(LabRptmain::getMainInfoId, mainInfoId);
        queryWrapper.eq(LabRptmain::getRptGroup, rptGroup).eq(LabRptmain::getSampleda, sampleda).eq(LabRptmain::getSampleNo, sampleNo);
        List<LabRptmain> labRptmainList = labRptmainMapper.selectList(queryWrapper);

        if (labRptmainList.isEmpty()) {
            return;
        }

        List<String> rptCodes = new ArrayList<>();//labRptmainList.stream().map(LabRptmain::getRptCode).collect(Collectors.toList());

        for (LabRptmain m : labRptmainList) {
            m.setDelFlag(1);
            rptCodes.add(m.getRptCode());
        }

        /*查询报告-细菌鉴定结果明细表*/
        LambdaQueryWrapper<LabRptdetailBac> queryWrapperBac = new LambdaQueryWrapper<>();
        queryWrapperBac.eq(LabRptdetailBac::getDelFlag, 0);
        queryWrapperBac.in(LabRptdetailBac::getRptMainCode, rptCodes);
        List<LabRptdetailBac> labRptdetailBacList = labRptdetailBacMapper.selectList(queryWrapperBac);

        for (LabRptdetailBac m : labRptdetailBacList) {
            m.setDelFlag(1);
        }

        /*查询报告-染色结果明细表*/
        LambdaQueryWrapper<LabRptdetailStaining> queryWrapperStaining = new LambdaQueryWrapper<>();
        queryWrapperStaining.eq(LabRptdetailStaining::getDelFlag, 0);
        queryWrapperStaining.in(LabRptdetailStaining::getRptMainCode, rptCodes);
        List<LabRptdetailStaining> labRptdetailStainingList = labRptdetailStainingMapper.selectList(queryWrapperStaining);
        for (LabRptdetailStaining m : labRptdetailStainingList) {
            m.setDelFlag(1);
        }

        if (labRptmainList.isEmpty()) {
            labRptmainService.updateBatchById(labRptmainList);
        }
        if (labRptdetailBacList.isEmpty()) {
            labRptdetailBacService.updateBatchById(labRptdetailBacList);
        }
        if (labRptdetailStainingList.isEmpty()) {
            labRptdetailStainingService.updateBatchById(labRptdetailStainingList);
        }
    }
}
